package es

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"month_zh5/common/model/mysql"
	"month_zh5/common/nacos"
	"time"
)

var client *elastic.Client

func InitEs() {
	var err error
	client, err = elastic.NewClient(elastic.SetURL(fmt.Sprintf("http://%s:%d",
		nacos.NacosConfig.Elastic.Host, nacos.NacosConfig.Elastic.Port,
	)), elastic.SetSniff(false))
	if err != nil {
		fmt.Print(err.Error())
		return
	}
}

func Create(e1 mysql.Goods, index string, id string) error {
	_, err := client.Index().
		Index(index).
		Id(id).
		BodyJson(e1).
		Do(context.Background())
	if err != nil {
		fmt.Print(err.Error())
		return err
	}
	return nil
}

type High struct {
	Took     int  `json:"took"`
	TimedOut bool `json:"timed_out"`
	Shards   struct {
		Total      int `json:"total"`
		Successful int `json:"successful"`
		Skipped    int `json:"skipped"`
		Failed     int `json:"failed"`
	} `json:"_shards"`
	Hits struct {
		Total struct {
			Value    int    `json:"value"`
			Relation string `json:"relation"`
		} `json:"total"`
		MaxScore float64 `json:"max_score"`
		Hits     []struct {
			Index  string  `json:"_index"`
			Type   string  `json:"_type"`
			Id     string  `json:"_id"`
			Score  float64 `json:"_score"`
			Source struct {
				ID             int         `json:"ID"`
				CreatedAt      time.Time   `json:"CreatedAt"`
				UpdatedAt      time.Time   `json:"UpdatedAt"`
				DeletedAt      interface{} `json:"DeletedAt"`
				GoodsName      string      `json:"GoodsName"`
				GoodsPrice     float64     `json:"GoodsPrice"`
				GoodsInventory int         `json:"GoodsInventory"`
				GoodsViews     int         `json:"GoodsViews"`
			} `json:"_source"`
		} `json:"hits"`
	} `json:"hits"`
}

func HSearch(text string) (High, error) {
	serrch, err := client.Search("goods").
		Query(elastic.NewMatchQuery("GoodsName", text)).
		Highlight(elastic.NewHighlight().
			Field("GoodsName").
			PreTags("<span style='color:red'>").
			PostTags("</span>")).
		Do(context.Background())

	if err != nil {
		return High{}, err
	}
	indent, err := json.MarshalIndent(serrch, "", "")
	if err != nil {
		return High{}, err
	}
	var high High
	err = json.Unmarshal(indent, &high)
	if err != nil {
		return High{}, err
	}
	return high, nil
}

func Search(text string) (High, error) {
	serrch, err := client.Search("goods").Query(elastic.NewMatchQuery("GoodsName", text)).Do(context.Background())

	if err != nil {
		return High{}, err
	}
	indent, err := json.MarshalIndent(serrch, "", "")
	if err != nil {
		return High{}, err
	}
	var high High
	err = json.Unmarshal(indent, &high)
	if err != nil {
		return High{}, err
	}
	return high, nil
}
